<!--suppress HtmlDeprecatedAttribute -->
<template>
  <div class="pageRoleSolidifyWrapper">
    <solidify-role-dialog v-model="dialogVisible" :id="dialogId" @update="freshAllTable"/>
    <xum-title class="title" title="查询条件" :title-span="8">
      <el-button @click="freshConditionForm" size="small" type="primary">重置</el-button>
      <el-button @click="freshAllTable" size="small" icon="el-icon-refresh" type="primary"
                 :disabled="paginationDisabled" :loading="paginationDisabled">查询</el-button>
    </xum-title>
    <el-form ref="form" :model="form" label-width="120px" size="small" :disabled="paginationDisabled">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="角色编号" prop="roleId">
            <el-input type="text" v-model="form.roleId" placeholder="角色编号"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="角色名称" prop="roleName">
            <el-input type="text" v-model="form.roleName" placeholder="角色名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="作用对象" prop="storeEmploy">
            <el-select v-model="form.storeEmploy" placeholder="作用对象">
              <el-option label="店铺管理员" :value="1"/>
              <el-option label="后台管理员" :value="0"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="top">
      <xum-title class="title" :title-span="6" title="固化角色列表">
        <el-button size="small" :icon="buttonsFlag ? 'el-icon-arrow-right' : 'el-icon-arrow-left'"
                   @click="buttonBox"/>
        <el-button v-if="buttonsFlag" @click="handleClearSort" size="small"
                   :disabled="paginationDisabled">清除排序</el-button>
        <el-button @click="handleRemoveMore" type="danger" size="small" icon="el-icon-delete-solid"
                   :disabled="paginationDisabled ? '' : null">删除选择</el-button>
      </xum-title>
    </div>
    <div class="table">
      <el-table ref="table" size="small" :data="tableData" style="width: 100%" height="449" max-height="600"
                v-loading='paginationDisabled' @selection-change="handleSelectionChange"
                :default-sort="tableSort" @sort-change="handleSortChange" :border="true">
        <el-table-column type="selection" align="center" width="50" fixed="left"/>
        <el-table-column prop="roleId" align="center" label="角色编号" columnKey="roleId"
                         resizable sortable="custom" width="150"/>
        <el-table-column prop="roleName" align="center" label="角色名称" columnKey="roleName"
                         resizable sortable="custom" width="150"/>
        <el-table-column prop="roleDesc" align="center" label="角色描述" columnKey="roleDesc"
                         resizable width="210"/>
        <el-table-column prop="roleBeginTime" align="center" label="开始时间" columnKey="roleBeginTime"
                         resizable sortable="custom" width="150"/>
        <el-table-column prop="roleEndTime" align="center" label="结束时间" columnKey="roleEndTime"
                         resizable sortable="custom" width="210"/>
        <el-table-column prop="storeEmploy" align="center" label="店铺使用标志" columnKey="storeEmploy"
                         resizable sortable="custom" width="210"/>
        <el-table-column prop="solidifyFlag" align="center" label="固化标志" columnKey="solidifyFlag"
                         resizable sortable="custom" width="210"/>
        <el-table-column prop="createTime" align="center" label="创建时间" columnKey="createTime"
                         resizable sortable="custom" width="210"/>
        <el-table-column prop="createUserId" align="center" label="创建人员编号" columnKey="createUserId"
                         resizable sortable="custom" width="210"/>
        <el-table-column prop="createUserName" align="center" label="创建人员名称" columnKey="createUserName"
                         resizable sortable="custom" width="210"/>
        <el-table-column prop="createUserType" align="center" label="创建人员类型" columnKey="createUserType"
                         resizable sortable="custom" width="210"/>
        <el-table-column prop="remark" align="center" label="备注" columnKey="remark"
                         resizable sortable="custom" width="210"/>
        <el-table-column label="操作" align="center" fixed="right" resizable width="200">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleDialogEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleRemove(scope.row)" style="color: red;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change='handleCurrentChange'
                     :page-size.sync='size' :total.sync="total" :current-page.sync="page" background
                     :disabled="paginationDisabled" layout="sizes, total, jumper, prev, pager, next"/>
    </div>
  </div>
</template>

<script>
import { ResultCode } from '@/constants/constants'
import PageDTO from '@/api/entity/PageDTO'
import BusinessConstants from '@/constants/BusinessConstants'
import XumTitle from '@/components/XumTitle'
import { queryAdminRolePageWrapper, removeAdminSolidifyRole } from '@/api/ApiRole'
import RoleQueryDTO from '@/api/entity/RoleQueryDTO'
import SolidifyRoleDialog from '@pages/resource/part/pageSolidifyRole/SolidifyRoleDialog'

export default {
  name: 'PageSolidifyRole',
  components: { SolidifyRoleDialog, XumTitle },
  data () {
    return {
      buttonsFlag: true,
      tableSort: {},
      dialogVisible: false,
      dialogId: 0,
      tableData: [],
      selection: [],
      sortData: this.tableSort,
      filterData: {},
      loading: false,
      total: 0,
      size: 10,
      page: 1,
      filterColumns: {
        category: [],
        group: [],
        sellPoint: [],
        state: []
      },
      form: {
        roleId: '',
        roleName: '',
        storeEmploy: '',
        solidifyFlag: ''
      }
    }
  },
  computed: {
    paginationDisabled () {
      return this.loading
    },
    selectIds () {
      const ids = []
      this.selection.forEach(item => {
        ids.push(item.roleId)
      })
      return ids
    }
  },
  methods: {
    buttonBox () {
      this.buttonsFlag = !this.buttonsFlag
    },
    /**
       * 打开编辑角色角色对话框
       * @param val 数据
       */
    handleDialogEdit (val) {
      this.dialogId = val.roleId
      this.dialogVisible = true
    },
    /**
       * 移除一个数据
       * @param val 数据
       */
    handleRemove (val) {
      if (val && val.roleId) {
        this.$confirm('此操作将永久删除该固化角色信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const id = val.roleId
          removeAdminSolidifyRole([id], data => {
            if (data.code === ResultCode.OK) {
              this.$message.success('移除角色成功')
              this.dialogVisible = false
              this.freshAllTable()
            }
          })
        }).catch(() => {
        })
      }
    },
    /**
       * 清除排序
       */
    handleClearSort () {
      this.$refs['table'].clearSort()
      this.sortData = {}
      this.freshAllTable()
    },
    /**
       * 清除筛选
       */
    handleClearFilter () {
      this.$refs['table'].clearFilter()
      this.filterData = {}
      this.page = 1
      this.freshAllTable()
    },
    /**
       * 移除选择的多个数据
       */
    handleRemoveMore () {
      if (this.selectIds.length === 0) {
        this.$message.error('请先选择希望移除的角色')
        return
      }
      this.$confirm('此操作将永久删除这' + this.selectIds.length + '条固化角色信息，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeAdminSolidifyRole(this.selectIds, data => {
          if (data.code === ResultCode.OK) {
            this.$message.success('移除角色成功')
            this.dialogVisible = false
            this.freshAllTable()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
       * 选择发生改变回调，同步数据
       * @param val 选择的数据，数组
       */
    handleSelectionChange (val) {
      this.selection = val
    },
    /**
       * 格式化时间格式
       * @param {Array} time 时间数组
       */
    formatTime (time) {
      if (!time) {
        return ''
      }
      for (let i = 1; i < time.length; i++) {
        time[i] = time[i] < 10 ? '0' + time[i] : '' + time[i]
      }
      return time[0] + '-' + time[1] + '-' + time[2] + ' ' + time[3] + ':' + time[4] + ':' + time[5]
    },
    freshConditionForm () {
      this.$refs.form.resetFields()
      this.form = {
        roleId: '',
        roleName: '',
        storeEmploy: '',
        solidifyFlag: ''
      }
    },
    freshAllTable () {
      this.freshTable()
    },
    /**
     * 更新表格数据，size和page改变时都会调用
     */
    freshTable () {
      this.loading = true
      const pageDTO = PageDTO.instance()
      pageDTO.setSize(this.size)
      pageDTO.setCurrent(this.page)
      const condition = RoleQueryDTO.instance()
        .setStoreEmploy(this.form.storeEmploy)
        .addStoreId(this.form.storeId)
        .addStoreName(this.form.storeName)
      // 排序
      if (this.sortData && this.sortData.prop && this.sortData.order) {
        if (this.sortData.order === 'descending') {
          condition.addOrderDesc(this.sortData.prop)
        } else if (this.sortData.order === 'ascending') {
          condition.addOrderAsc(this.sortData.prop)
        }
      }
      // 筛选
      Object.keys(this.filterData).forEach(key => {
        if (this.filterData[key].length > 0) {
          condition.addFilter(key, this.filterData[key])
        }
      })
      condition
        .setSolidifyFlag(1)
        .addManageType(BusinessConstants.USER_TYPE_ADMIN)
      pageDTO.setCondition(condition)
      queryAdminRolePageWrapper(pageDTO, data => {
        if (data.code === ResultCode.OK) {
          this.tableData = data.object['records']
          this.tableData.forEach(item => {
            item.createTime = this.formatTime(item['createTime'])
            item.roleBeginTime = this.formatTime(item['roleBeginTime'])
            item.roleEndTime = this.formatTime(item['roleEndTime'])
            if (item.storeEmploy) {
              if (item.storeEmploy === 1) {
                item.storeEmploy = '店铺管理员'
              } else if (item.storeEmploy === 0) {
                item.storeEmploy = '后台管理员'
              }
            } else {
              item.storeEmploy = '后台管理员'
            }
            if (item.solidifyFlag) {
              if (item.solidifyFlag === 1) {
                item.solidifyFlag = '固化角色'
              } else {
                item.solidifyFlag = '非固化角色'
              }
            } else {
              item.solidifyFlag = '非固化角色'
            }
          })
          this.total = data.object['total']
        }
      }, () => {
        this.loading = false
      })
    },
    /**
       * size改变更新数据
       */
    handleSizeChange () {
      this.page = 1
      this.freshTable()
    },
    /**
       * 排序改变监听，刷新页面
       * { column, prop, order }
       */
    handleSortChange (val) {
      this.sortData = val
      this.freshTable()
    },
    /**
       * 筛选改变监听
       */
    handleFilterChange (val) {
      Object.assign(this.filterData, val)
      this.page = 1
      this.freshTable()
    },
    /**
       * page改变更新数据
       */
    handleCurrentChange () {
      this.freshTable()
    }
  },
  mounted () {
    this.freshTable()
  }
}
</script>

<style scoped lang="scss">
  .pageRoleSolidifyWrapper{

    .title{
      line-height: 220%;
    }

    .table {
      margin: 16px 0;
      text-align: center;

      .pagination {
        margin: 20px auto;
      }
    }

  }
</style>
